package com.cheyunkeji.er.activity.fast_evaluate;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ScrollView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.evaluate.PhotoPreViewActivity;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.fragment.fast_evaluate.FastEvaluateFragment;
import com.cheyunkeji.er.service.OssService;
import com.cheyunkeji.er.utils.ImageLoadUtil;
import com.cheyunkeji.er.view.TopBar;
import com.cheyunkeji.er.view.evaluate.ImageSelectDialog;
import com.cheyunkeji.er.view.evaluate.TakePhotoDisplayView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.utils.ImageCaptureManager;

/**
 * @author Michael
 * @date 2018/1/25
 */
public class FastEvaluateMorePicturesActivity extends BaseActivity
    implements TakePhotoDisplayView.OnTakePhotoListener, ImageSelectDialog.ImageSelectListener {

  private static final int PREVIEW_IMG_REQUEST = 0x1001;
  private static final String TAG = FastEvaluateMorePicturesActivity.class.getSimpleName();

  @BindView(R.id.v_topbar)
  TopBar vTopbar;

  @BindView(R.id.tpdv_01)
  TakePhotoDisplayView tpdv01;

  @BindView(R.id.tpdv_02)
  TakePhotoDisplayView tpdv02;

  @BindView(R.id.tpdv_03)
  TakePhotoDisplayView tpdv03;

  @BindView(R.id.tpdv_04)
  TakePhotoDisplayView tpdv04;

  @BindView(R.id.tpdv_05)
  TakePhotoDisplayView tpdv05;

  @BindView(R.id.tpdv_06)
  TakePhotoDisplayView tpdv06;

  @BindView(R.id.tpdv_07)
  TakePhotoDisplayView tpdv07;

  @BindView(R.id.tpdv_08)
  TakePhotoDisplayView tpdv08;

  @BindView(R.id.sv_content)
  ScrollView svContent;

  /** 图片选择 Dialog */
  private ImageSelectDialog imgSelectDialog;

  /** 系统相机 Manager */
  private ImageCaptureManager captureManager;

  /** 图片控件 List 集合 */
  private List<TakePhotoDisplayView> photoViewList;

  /** view 的hashcode，作为 key 获取图片路径 path */
  private int[] viewHashCode = new int[8];

  private Map<Integer, String> picturePathSet = new HashMap<>(8);

  @Override
  protected void init() {
    setContentView(R.layout.er_activity_fast_evaluate_more_pictures);
    ButterKnife.bind(this);
    captureManager = new ImageCaptureManager(this);
  }

  @Override
  protected void initView() {
    vTopbar.setTitle("更多照片");
    vTopbar.setLeftBack();
    vTopbar.setRight("保存", -1, this);

    photoViewList = new ArrayList<>();
    photoViewList.add(tpdv01);
    photoViewList.add(tpdv02);
    photoViewList.add(tpdv03);
    photoViewList.add(tpdv04);
    photoViewList.add(tpdv05);
    photoViewList.add(tpdv06);
    photoViewList.add(tpdv07);
    photoViewList.add(tpdv08);

    for (int i = 0; i < photoViewList.size(); i++) {
      photoViewList.get(i).setListener(this);
      viewHashCode[i] = photoViewList.get(i).hashCode();
      picturePathSet.put(photoViewList.get(i).hashCode(), "");
    }
  }

  @Override
  protected void initData() {
    String[] pictureArray = getIntent().getStringArrayExtra(FastEvaluateFragment.MORE_PICTURE);
    if (pictureArray != null && pictureArray.length != 0) {
      //          设置并初始化图片
      for (int i = 0; i < pictureArray.length; i++) {
        if (!TextUtils.isEmpty(pictureArray[i])) {
          photoViewList.get(i).setImgPath(pictureArray[i]);
          ImageLoadUtil.loadImg(this, pictureArray[i], photoViewList.get(i).getImageView());
          photoViewList.get(i).setPhotoBtnState(true);
          picturePathSet.put(photoViewList.get(i).hashCode(), pictureArray[i]);
        }
      }
    }
  }

  @Override
  public void takePhoto(int itemIndex) {
    //      标记当前弹出 Dialog 的 TakePhotoDisplayView
    svContent.setTag(itemIndex);

    if (!TextUtils.isEmpty(photoViewList.get(itemIndex).getImagePath())) {
      //          有照片，预览照片
      Intent intent = new Intent(this, PhotoPreViewActivity.class);
      intent.putExtra("IMG_PATH", photoViewList.get(itemIndex).getImagePath());
      this.startActivityForResult(intent, PREVIEW_IMG_REQUEST);
    } else {
      showImgSelectDialog(photoViewList.get(itemIndex).getTextDesc());
    }
  }

  /**
   * 弹出弹框
   *
   * @param titleStr 弹框 title
   */
  public void showImgSelectDialog(String titleStr) {
    if (null == imgSelectDialog) {
      imgSelectDialog = new ImageSelectDialog(this, this, titleStr);
    } else {
      imgSelectDialog.setTitleStr(titleStr);
    }
    imgSelectDialog.show();
  }

  @Override
  public void onClick(View v) {
    super.onClick(v);
    if (v.getId() == R.id.vRight) {
      checkAndUploadImg();
    }
  }

  /** 用户返回时，检查图片并上传至阿里云 */
  private void checkAndUploadImg() {
    /** 1. 过滤图片路径，如果不是以 http 或 https 开头，需要进行上传 2. OSS 图片上传 3. 上传成功，修改集合对应的图片链接，上传失败，容错处理 ！ */
    saveImgPathToArray();

    if (picturePathSet.isEmpty() || isPicturePathSetIsNone()) {
      Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show();
      return;
    } else {
      Log.e(TAG, "checkAndUploadImg: " + picturePathSet);
    }

    showDialog();

    Observable.fromIterable(picturePathSet.keySet())
            .filter(
                    new Predicate<Integer>() {
                      @Override
                      public boolean test(Integer key) throws Exception {
                        //                        筛选本地图片
                        Log.e(TAG, "筛选图片结果 ： " + picturePathSet.get(key));
                        return !TextUtils.isEmpty(picturePathSet.get(key))
                                && !picturePathSet.get(key).startsWith("http://")
                                && !picturePathSet.get(key).startsWith("https://");
                      }
                    })
            .map(
                    new Function<Integer, OssService.OssUnit>() {
                      @Override
                      public OssService.OssUnit apply(Integer viewHash) throws Exception {
                        return MyApplication.getInstance().getOssService(null)
                                .synchronizePutImage(
                                        OssService.getOssObjectInfo(true),
                                        picturePathSet.get(viewHash),
                                        getIndexOfHashCodes(viewHash));
                      }
                    })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    new Observer<OssService.OssUnit>() {
                      @Override
                      public void onSubscribe(Disposable d) {
                        Log.e(TAG, "onSubscribe: ");
                      }

                      @Override
                      public void onNext(OssService.OssUnit ossUnit) {
                        Log.e(TAG, "onNext:  Path : " + ossUnit.getPath() + "\n Tag  : " + ossUnit.getTag());
                        photoViewList.get((Integer) ossUnit.getTag()).setImgPath(ossUnit.getPath());
                      }

                      @Override
                      public void onError(Throwable e) {
                        dismissDialog();
                        //                      网络错误
                        if (e instanceof ClientException) {
                          Toast.makeText(FastEvaluateMorePicturesActivity.this, "请检查网络连接", Toast.LENGTH_SHORT).show();
                          return;
                        }
                        Toast.makeText(FastEvaluateMorePicturesActivity.this, "图片上传失败", Toast.LENGTH_SHORT).show();
                      }

                      @Override
                      public void onComplete() {
                        Log.e(TAG, "onComplete: ");
                        dismissDialog();
                        saveImgPathToArray();
                        setReturnData();
                      }
                    });
  }

  /**
   * 判断是否选择了图片
   *
   * @return
   */
  private boolean isPicturePathSetIsNone() {
    for (String path : picturePathSet.values()) {
      if (!TextUtils.isEmpty(path)) {
        return false;
      }
    }
    return true;
  }

  /** 设置返回数据 */
  private void setReturnData() {
    Intent intent = new Intent();
    intent.putExtra(FastEvaluateFragment.MORE_PICTURE, getImagePathArray());
    FastEvaluateMorePicturesActivity.this.setResult(Activity.RESULT_OK, intent);

    //        提交成功是否返回
    MyApplication.getInstance().removeActivity(this.getClass());
    finish();
  }

  /**
   * 获取最终图片 OSS 路径
   *
   * @return
   */
  private String[] getImagePathArray() {
    String[] imgPathArray = new String[8];
    for (int i = 0; i < viewHashCode.length; i++) {
      imgPathArray[i] = picturePathSet.get(viewHashCode[i]);
    }

    for (String path : imgPathArray) {
      Log.e(TAG, " ============= getImagePathArray 最终图片路径 ： " + path);
    }

    return imgPathArray;
  }

  /**
   * 获取 TakePhotoDisplayView 的 HashCode ，并在HashMap中作为获取图片路径的 key
   *
   * @param viewHash
   * @return
   */
  private int getIndexOfHashCodes(Integer viewHash) {
    int temp = -1;
    for (int i = 0; i < viewHashCode.length; i++) {
      if (viewHashCode[i] == viewHash) {
        temp = i;
        break;
      }
    }
    return temp;
  }

  /** 将当前图片的路径保存到数组当中 */
  private void saveImgPathToArray() {
    for (int i = 0; i < photoViewList.size(); i++) {
      if (!TextUtils.isEmpty(photoViewList.get(i).getImagePath())) {
        picturePathSet.put(photoViewList.get(i).hashCode(), photoViewList.get(i).getImagePath());
      }
    }
  }

  @Override
  public void onBackPressed() {
    setReturnData();
    super.onBackPressed();
  }

  @Override
  public void onTakePhotoWithSystemCamera() {
    openSystemCamera();
  }

  @Override
  public void onSelectImgOnGallery() {
    pickPhoto();
  }

  /** 打开图片选择器 */
  private void pickPhoto() {
    PhotoPicker.builder().setPhotoCount(1).start(this);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        /** 相册图片选择返回结果 */
      case PhotoPicker.REQUEST_CODE:
        if (data != null) {
          String localImgPath =
              data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS).get(0);
          if (!TextUtils.isEmpty(localImgPath)) {

            photoViewList.get((int) svContent.getTag()).setImgPath(localImgPath);
            photoViewList.get((int) svContent.getTag()).setPhotoBtnState(true);
            ImageLoadUtil.loadImg(
                this, localImgPath, photoViewList.get((int) svContent.getTag()).getImageView());
          }
        }
        break;
        /** 系统相机拍摄返回图片 path */
      case ImageCaptureManager.REQUEST_TAKE_PHOTO:
        if (resultCode == RESULT_OK) {
          captureManager.galleryAddPic();

          String path = captureManager.getCurrentPhotoPath();
          photoViewList.get((int) svContent.getTag()).setImgPath(path);
          photoViewList.get((int) svContent.getTag()).setPhotoBtnState(true);
          ImageLoadUtil.loadImg(
              this, path, photoViewList.get((int) svContent.getTag()).getImageView());
        }
        break;
        /** 图片预览返回结果 */
      case PREVIEW_IMG_REQUEST:
        if (data == null) {
          return;
        }

        boolean deleteImg = data.getBooleanExtra("DELETE_IMG", false);

        if (deleteImg) {
          photoViewList.get((int) svContent.getTag()).setImgPath("");
          photoViewList.get((int) svContent.getTag()).setPhotoBtnState(false);
          photoViewList.get((int) svContent.getTag()).getImageView().setImageDrawable(null);

          picturePathSet.put(viewHashCode[(int) svContent.getTag()], "");
        }
        break;

      default:
        break;
    }
  }

  private void openSystemCamera() {
    Intent intent = null;
    try {
      intent = captureManager.dispatchTakePictureIntent();
      startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    captureManager = null;
  }
}
